package com.inforich.app.component;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.inforich.app.constant.AuthConstants;
import com.inforich.common.exception.user.AppAuthException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

  private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
  @Autowired
  private TokenUtil tokenUtil;
  @Autowired
  public StringRedisTemplate redisTemplate;

  /**
   * 在请求被处理之前调用
   *
   * @param request  请求
   * @param response 返回
   * @param handler
   * @return Boolean
   * @throws Exception
   */
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String url = request.getRequestURI();
    System.out.println("请求地址: " + url);
    // 从header中获取token
    String token = request.getHeader("Authorization");
    if (StrUtil.isBlank(token)) {
      fastFailureResponse(response);
      return false;
    }
    token = token.replace("Bearer ", "");
    if (StrUtil.isBlank(token)) {
      fastFailureResponse(response);
      return false;
    }
    // 从token中获取登录信息
    LoginUserApp loginUserApp = tokenUtil.getLoginUserApp(token);
    if (loginUserApp == null) {
      fastFailureResponse(response);
      return false;
    }
    // 校验token是否有效
//    String tokenCache = redisTemplate.opsForValue().get(AuthConstants.REDIS_CACHE_APP + userId);
//    if (!token.equals(tokenCache)) {
//      fastFailureResponse(response);
//      return false;
//    }
    // 校验当前用户是否有对应的请求权限
    if (handler instanceof HandlerMethod) {
      HandlerMethod h = (HandlerMethod) handler;
      PreAppRole preAppRole = h.getMethodAnnotation(PreAppRole.class);
      if (preAppRole != null) {
        String requireRoleCode = preAppRole.value();
        String roleCode = loginUserApp.getRoleCode();
        if (StrUtil.isBlank(roleCode) || !roleCode.equals(requireRoleCode)) {
          fastFailureResponse(response, "当前用户没有对应的权限");
        }
      }
    }
    // 将用户登录信息存入，在controller方法中使用
    request.setAttribute(AuthConstants.USER_CURRENT, loginUserApp);
    return true;
  }

  /**
   * 请求失败返回
   */
  private static void fastFailureResponse(HttpServletResponse response) throws IOException {
    fastFailureResponse(response, "无效的TOKEN");
  }

  private static void fastFailureResponse(HttpServletResponse response, String msg) {
    throw new AppAuthException(msg);
  }
}
